﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VDataAdapter.BlockingQueue;
using log4net;


namespace VDataAdapter
{
    public class VndDequeue
    {
        CommunicationDataQueue _mainQueue;
        string _filePath;
        private readonly ILog _log = LogManager.GetLogger(typeof(VndDequeue));
        public VndDequeue(CommunicationDataQueue mainQueue, string filePath)
        {
            _mainQueue = mainQueue;
            _filePath = filePath;
        }

        public void Start()
        {           
            CommunicationData obj = null;
            string message;
            while(true)
            {
                // Nhan du lieu tu queue and send to client
                obj = null;
                obj = _mainQueue.get();
                if (obj != null)
                {
                    try
                    {
                        message = GetMsgFromCommunicationData(obj);
                        AddToFile(message);                         
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Error get message and write to file: " + ex.Message);
                    }
                }
            }
        }

        protected string GetMsgFromCommunicationData(CommunicationData obj)
        {
            BaseObject objBaseObject = obj.getBaseObjectData();
            DataQueue objDataQueue = obj.getDataQueue();
            string sClassName = objBaseObject.getObjectType();
            MessageObject objMessage = (MessageObject)objBaseObject;
            return objMessage.getMsg();
        }

        /// <summary>
        /// Add to the message to file
        /// </summary>
        /// <param name="msg"></param>
        public void AddToFile(string msg)
        {
            // Write the string to a file.
            try
            {
                System.IO.StreamWriter file = new System.IO.StreamWriter(_filePath, true);
                file.WriteLine(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss") + ": " + msg);
                file.Flush();
                file.Dispose();
                file.Close();
            }
            catch (Exception ex)
            {
                throw new Exception("Error writing to file VndDequeue: " + ex.Message);
            }
        }
    }
}
